package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.UserUtils;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.MovieCommentDao;
import com.lcf.system.dto.MovieCommentDTO;
import com.lcf.system.entity.Movie;
import com.lcf.system.entity.MovieComment;
import com.lcf.system.query.MovieCommentPageQuery;
import com.lcf.system.service.MovieCommentService;
import com.lcf.system.vo.MovieCommentVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 评论(MovieComment)表服务实现类
 *
 * @author lcf
 * @since 2025-05-07 22:23:22
 */
@Service("movieCommentService")
public class MovieCommentServiceImpl extends ServiceImpl<MovieCommentDao, MovieComment> implements MovieCommentService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void comment(MovieCommentDTO dto) {
        MovieComment comment = BeanUtil.copyProperties(dto, MovieComment.class);
        comment.setUserId(UserUtils.getUserId());
        comment.insert();

        Db.lambdaQuery(Movie.class).eq(Movie::getId, dto.getMovieId()).oneOpt().ifPresent(x -> {
            x.setCommentTimes(x.getCommentTimes() + 1);
            x.updateById();
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Db.lambdaQuery(MovieComment.class).eq(MovieComment::getId, id).oneOpt().ifPresent(x -> {
            removeById(id);

            Db.lambdaQuery(Movie.class).eq(Movie::getId, x.getMovieId()).oneOpt().ifPresent(m -> {
                m.setCommentTimes(Math.max(m.getCommentTimes() - 1, 0));
                m.updateById();
            });
        });
    }

    @Override
    public PageVO<MovieCommentVO> page(MovieCommentPageQuery query) {
        Page<MovieComment> page = Db.lambdaQuery(MovieComment.class)
                .eq(query.getUserId() != null, MovieComment::getUserId, query.getUserId())
                .eq(query.getMovieId() != null, MovieComment::getMovieId, query.getMovieId())
                .orderByDesc(MovieComment::getCreateTime)
                .page(query.toPage());
        return new PageVO<>(page, MovieCommentVO.class);
    }
}

